package gspushmq.v1.produce.job.hq;

import com.alibaba.fastjson.JSONObject;
import ggframework.mongodb.BasicDBObject;
import ggframework.mongodb.DBCollection;
import ggframework.mongodb.DBObject;
import ggframework.mongodb.GGMongoOperator;
import ggframework.util.GGConfigurer;
import gspushmq.model.*;
import gspushmq.util.DateUtil;
import gspushmq.util.GGLogger;
import gspushmq.util.MongoUtil;
import gspushmq.util.SysUtil;
import gspushmq.v1.consumer.core.MessageQueue;
import gspushmq.v1.produce.job.sys.GGMQRealTimeJob;
import org.apache.commons.lang3.StringUtils;
import org.java_websocket.WebSocket;

import java.util.Date;

/**
 * @Description 处理行情相关消息
 * @Author chengsj
 * @Date 2018/12/7 16:47
 * @Version 1.0
 * @company 上海朝阳永续信息技术有限公司
 * @copyright (c) 2015 SunTime Co'Ltd Inc. All rights reserved.
 **/
public class HQService {


    /**
     * @param
     * @description 行情业务入口
     * @version 1.0
     * @author chengsja
     * @date 2018/12/14 15:52
     */
    public static void dealHqWarn(Message message, WebSocket ws) {
        JSONObject map_message = getMapMessage(message);
        if (map_message == null) {
            //fail
            ws.send("闪电预警设置失败！");
            return;
        }
        //
        Long id = map_message.getLong("id");
        //
        Integer delete = map_message.getInteger("delete");
        if (id != null && Integer.valueOf(1).equals(delete)) {
            // 0 删除 1 发送过来的 2 在线已发 3 已经预警，未发送
            updateStockCode(map_message, HQwarnEnum.DEL.getCode());
            GGLogger.info(HQService.class, "---> 接收客户端闪取消电预警消息成功!msg=" + map_message);
        } else {
            id = saveHqStockWarnBase(map_message, HQwarnEnum.WARNING.getCode());
            map_message.put("id", id);
            GGLogger.info(HQService.class, "---> 接收客户端闪设置电预警消息成功!msg=" + map_message);
        }
        //投递mq
        GGMQRealTimeJob.sendMQ(GGConfigurer.get("STOCK_EFFECT",GGQueueConstant.STOCK_EFFECT), map_message.toJSONString());
        //success
        ws.send("闪电预警设置成功！");
    }


    /**
     * @param
     * @description 兼容老mq消息结构处理
     * @version 1.0
     * @author chengsja
     * @date 2018/12/14 15:52
     */
    private static JSONObject getMapMessage(Message message) {
        if (message == null) {
            return null;
        }
        String accountId = message.getAccount_id();
        String productLine = message.getProduct_line();
        Integer mesType = 10001;
        String paramsMessage = message.getParams();
        if (StringUtils.isBlank(accountId) ||
                StringUtils.isBlank(productLine) ||
                StringUtils.isBlank(paramsMessage)) {
            return null;
        }

        JSONObject paramsJSON = JSONObject.parseObject(paramsMessage);
        String fullCode = paramsJSON.getString("fullcode");
        String params = paramsJSON.getString("params");

        // 可选参数配置id,delete
        String id = paramsJSON.getString("id");
        Integer delete = paramsJSON.getInteger("delete");
        boolean b = StringUtils.isBlank(fullCode) ||
                StringUtils.isBlank(params);
        //设置
        if (id == null && b) {
            return null;
        }

        JSONObject mapMessage = new JSONObject();
        mapMessage.put("request_id", accountId + "&" + productLine);
        mapMessage.put("fullcode", fullCode);
        mapMessage.put("mes_type", mesType);
        mapMessage.put("params", params);
        // 可选参数配置id,delete
        if (id != null && Integer.valueOf(1).equals(delete)) {
            mapMessage.put("id", id);
            mapMessage.put("delete", delete);
        }
        return mapMessage;
    }



    /**
     * @param
     * @description 更新客户端发送的行情预警信息
     * @version 1.0
     * @author chengsja
     * @date 2018/12/14 15:53
     */
    private static void updateStockCode(JSONObject map_message, Integer status) {
        DBCollection collection = MongoUtil.getFtMixCollection("cp_msg_stock_code");

        Long id = map_message.getLongValue("id");

        DBObject query = new BasicDBObject();
        query.put("_id", id);

        DBObject object = new BasicDBObject();
        // 0 为达表准 1已推送数据 2 微推送数据
        object.put("status", status);
        object.put("content", map_message);
        object.put("update_time", new Date());

        collection.update(query, new BasicDBObject("$set", object));
    }


    /**
     * @param
     * @description 保存客户端发送的行情预警消息
     * @version 1.0
     * @author chengsja
     * @date 2018/12/14 15:53
     */
    private static Long saveHqStockWarnBase(JSONObject map_message, Integer status) {
        DBCollection collection = MongoUtil.getFtMixCollection("cp_msg_stock_code");

        String request_id = map_message.getString("request_id");
        String mes_type = map_message.getString("mes_type");

        BasicDBObject value = GGMongoOperator.newDBObject(collection)
                .append("request_id", request_id)
                .append("mes_type", mes_type)
                .append("content", map_message)
                .append("status", status)
                .append("tmstampe", System.currentTimeMillis())
                .append("create_time", new Date())
                .append("update_time", new Date());

        collection.insert(value);
        return value.getLong("_id");
    }

    /**
     * @param
     * @description 接收预警的消息入口
     * @version 1.0
     * @author chengsja
     * @date 2018/12/14 15:49
     */
    public static void receiveHqMessage(JSONObject map_message) {
        String stockName = map_message.getString("name");
        Date date = map_message.getDate("update_time");
        //83456&28
        String consumer = map_message.getString("request_id");
        String fullCode = map_message.getString("fullcode");
        if (StringUtils.isBlank(stockName) || date == null
                || StringUtils.isBlank(consumer) || StringUtils.isBlank(fullCode)) {
            GGLogger.info(GGMQRealTimeJob.class, "接收无效预警消息map_message" + map_message);
            return;
        }
        String[] accountIdAndProductLine = consumer.split("&");
        if (accountIdAndProductLine.length != 2) {
            return;
        }
        GGLogger.info(GGMQRealTimeJob.class, "接收预警成功消息map_message" + map_message);
        String content = map_message.getString("params");
        content = formatString(content);
        //生产消息入库
        DataMessage dataMessage = new DataMessage();
        dataMessage.setMqType(PrefixEnum.HQ.getMqType());
        dataMessage.setMqSubType(PrefixEnum.HQ.getMqSubType());
        dataMessage.setContent(DateUtil.dateToString(date,"yyyy-MM-dd HH:mm:ss") +" "+ stockName + content);
        dataMessage.setTitle(stockName+content);
        dataMessage.setCrowdType(ConsumerWays.ALIAS.getWay());
        //账号id
        dataMessage.setCrowdValue(accountIdAndProductLine[0]);
        //内链
        dataMessage.setLinkType(LinkEnum.INNER.getLinkType());
        //模块id
        dataMessage.setModule(SkipConstant.HQ_WARN_MODULE);
        //target为股票代码
        dataMessage.setTarget(fullCode);
        //产品线
        dataMessage.setProductLine(Integer.valueOf(accountIdAndProductLine[1]));

        dataMessage.setStartDate(date);
        //1天过期
        dataMessage.setExpireDate(DateUtil.getAfterDate(date, 1));
        //入库
        SysUtil.sendToMongo(dataMessage);
        
        
        //在线消息池
        MessageQueue.messageQueue.add(dataMessage);
        
        
        //更新预警状态
        HQService.updateStockCode(map_message, HQwarnEnum.WARNED.getCode());
    }

    /**
     *
     * @description 格式化行情预警消息内容样式
     * @param content 原始字符串
     * @version 1.0
     * @author chengsja
     * @date 2018/12/21 13:03
     *
     */
    private static String formatString(String content){

        String prefix = "";
        String suffix = "";
        String key = "";
        //涨跌幅格式
        if (content.contains("price_change_rate")) {
            key = "price_change_rate";
            suffix = "%";
            if (content.contains(">")) {
                prefix = "涨幅突破";
            } else if (content.contains("<")) {
                prefix = "跌幅达到";
            }
        }else if (content.contains("turnover_rate")) {
            key = "turnover_rate";
            suffix = "%";
            prefix = "换手率达到";
        }else if (content.contains("price")){
            key = "price";
            suffix = "元";
            if (content.contains(">")) {
                prefix = "最新价突破";
            } else if (content.contains("<")) {
                prefix = "最新价跌破";
            }
        }
        content = StringUtils.replace(content, key, prefix);
        content = StringUtils.replace(content, ">", "");
        content = StringUtils.replace(content, "=", "");
        content = StringUtils.replace(content, "<", "");
        return content+ suffix;
    }

}
